// Example6.java

package com.ibm.tspaces.examples.simple;

import  java.util.*;
import  java.text.*;
import  java.io.*;

import  com.ibm.tspaces.*;
/*
**  Licensed Materials - Property of IBM
**
**  (C) COPYRIGHT IBM Corp. 1996, 1997  All rights reserved
**
**  US Government Users Restricted Rights - Use, duplication or
**  disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
**
**/
/**
** This class will show the use of a number of unrelated TSpaces commands.
**
**	
**   Use the "status" method to check the TSpaces server status
**
**   Create a TupleSpace object for a TupleSpace named "Example6"
**   at the Host specified as the 1st operand. (default localhost)
**     - If this space does not already exist, it will be created.
**
**   Use the "status" method to check the TSpaces server status
**
**   Use the MultiWrite method to efficiently write 20 Tuples to the 
**   database.
**   
**   Write a Tuple and then use Update to update it.
**   
**   Write a Tuple, use the uniqueId returned from write()  
**   with DeleteByTupleId to delete it.
**
**   
** @see TupleSpace
** @version $Revision: 2.1 $ $Date: 1999/11/05 22:22:39 $
** @author John Thomas
*/

public class Example6 {
			
	
public static void 
main( String argv[] ) {
  
	//Debug.setDebugOn(true);
	
  String	host	=	"localhost";
  	
  String MyTsName = "Example6";
	
	if (argv.length == 0) 
		Debug.out("Syntax:  ServerHost SpaceName");
	if (argv.length > 0) 
      	host = argv[0];      // if user specified server host
  if (argv.length > 1) 
    	MyTsName = argv[1];      // if user specified tsname
	
  try {
    // Get the level of the TSpace client support
    Debug.out("T Spaces Version = " + TupleSpace.getVersion());
    
    // Get the status of the server    
	  Tuple active = TupleSpace.status(host,TupleSpace.DEFAULTPORT);
    // 
    if ( active == null || active.getField(0).getValue().equals("NotRunning")) {
      Debug.out(0,"Server not running on " +   host );
      return;
    }  else  {
      Debug.out(0,"TSpaces Server: Version = "+active.getField(1).getValue());
    } 

    
    // Check if the Space exists.
    boolean exists = TupleSpace.exists(MyTsName,host,TupleSpace.DEFAULTPORT);
    Debug.out("Space "+MyTsName+" exists = "+exists);
    
		// Create a Tuple describing the configuration
		
    ConfigTuple config = new ConfigTuple();
    config.setOption(ConfigTuple.PERSISTENCE, new Boolean( false) );
  	config.setOption(ConfigTuple.TSDBTYPE,TupleSpace._DBTYPE_MMDB);
	
		Debug.out("Attempting to open Server  "+MyTsName+"@"+host);
		// Create the new Space 
	
		TupleSpace ts = new TupleSpace(MyTsName,host,TupleSpace.DEFAULTPORT,config);
		int count = ts.countN(new Tuple());
		if (count > 0) {
    			// Clear out the space
    			ts.deleteAll();
    			Debug.out("Cleaned up "+count+" old tuples");
		}
		// Write the data using multiWrite method.  						
		
    try {
      Tuple multi = new Tuple();
			for (int i=0; i<10;i++) {						
			   Tuple nextTuple = new Tuple("Test6 MultiWrite",new Integer(i),"Tuple# "+(i+1)+" of 10");
			   multi.add(new Field(nextTuple));  
			}
      
      ts.multiWrite(multi);
        
      Debug.out("Wrote "+multi);
      
      count = ts.countN(new Tuple());
      if (count != 10) {
         Debug.out(Debug.ALWAYS,"ERROR - Space contains  "+count + " instead of 10 tuples");
        System.exit(1);
      }
      // get all the Tuples and modify each one 
      Tuple template = new Tuple();
      Tuple all = ts.scan(template);
      Enumeration e = all.fields();
      while (e.hasMoreElements()) {
        Tuple t =(Tuple)((Field)e.nextElement()).getValue();
        //Debug.out(t);
        t.getField(0).setValue("Test6 MultiUpdate");
      }
      ts.multiUpdate(all);
    	Debug.out("Updated: "+ all);	
		} catch (Exception e) {	
			Debug.out(e);
		}
	    
	  // Use the Tuple uniqueId field
		// Now write a tuple, update it and  then delete that specific tuple 
		
		try { 
			
			Tuple newTuple = new Tuple("Test6",new Integer(99),"This should be updated");	
			
			TupleID id= ts.write(newTuple);
			Debug.out("Wrote "+newTuple+ " as id="+id);
			
		
			Tuple updatedTuple = new Tuple("Test6",new Integer(99),"Updated - will be deleted next");  
			id = ts.update(id,updatedTuple);
			Debug.out("Updated "+updatedTuple+ " as id="+id);
      SuperTuple readback = ts.readTupleById(id);
      if ( (readback == null) || (! readback.matches(updatedTuple)) ) {
        Debug.out(0,"ReadTupleById failed for:"+ id );
        System.exit(1);
      } else
        Debug.out("ReadByTupleID succeeded");


			ts.deleteTupleById(id);
			Tuple template = new Tuple("Test6",new Integer(99),new Field(String.class) );  
			Tuple checkIt = (Tuple)ts.read(template);
			if (checkIt != null) {
				Debug.out(0,"DeleteTupleById failed for"+ checkIt );
				System.exit(1);
			} else
        Debug.out("DeleteByTupleID succeeded");
		
		}   catch(TupleSpaceException tse) {
      		Debug.out(tse);	
      
    }  
    		
    // Another test 
		
		try { 
			
			Tuple original = new Tuple("Test6",new Integer(5),"Should be updated");
			TupleID id = ts.write(original);
			Debug.out("Write "+original+" as "+id);

			Tuple template5 = new Tuple("Test6",new Integer(5),new Field(String.class));
			Tuple newTuple = new Tuple("Test6",new Integer(5),"Update Tuple# 5");
      
			
			id = ts.update(template5,newTuple);
			Debug.out("Updated "+newTuple+" as "+id);
			Tuple check5 = (Tuple)ts.readTupleById(id);
			Debug.out("ReadTupleById = "+ check5 );
			
			// We will delete the tuple and then try to update it
			// It had better throw an exception
			try {
        ts.delete(template5);
        //id = ts.update(template5,newTuple);
			
			  //Debug.out(Debug.ALWAYS,"Error: Update of deleted Tuple should have thrown exception");
				//System.exit(1);
			} catch (Exception e) {
				//Debug.out("OK, correctly threw the following exception");
				//Debug.out(e.getMessage());
        //Debug.out(0,"Note: Example 6 will cause an Exception message at the server. This is OK");
      }
       
			// at this point, there should be 10 tuples left in the space.		
			int countu = ts.countN(new Tuple());
    	if (countu != 10) {
         Debug.out(Debug.ALWAYS,"ERROR - Space contains  "+countu + " instead of 10 tuples");
        System.exit(1);
      }
	
		 Debug.out(0,"Example6 was successful");
			
		}   catch(TupleSpaceException tse) {
      		Debug.out(tse);	
      
    }   		

    		
		TupleSpace.cleanup();
	
		System.exit(1);

      
    } catch(Exception tse) {
      Debug.out("Exception: " + tse.getMessage());	
      tse.printStackTrace();
    }      
  }
}
/* $Log: Example6.java,v $
/* Revision 2.1  1999/11/05 22:22:39  estesp
/* Update revision number to 2.1 on all files
/*
/* Revision 1.1.1.1  1999/11/05 16:24:53  estesp
/* Imported 2.1.0 release into Austin CVS
/*
 * Revision 1.8  1999/10/08 02:14:04  jthomas
 * minor debug output change
 *
 * Revision 1.7  1999/10/06 00:55:23  jthomas
 * cleanup the messages displayed on a normal run
 *
 * Revision 1.6  1999/09/08 15:31:37  jthomas
 * Make the tests more self checking and easier to run
 *
 * Revision 1.5  1999/07/30 00:50:11  esakki
 * *** empty log message ***
 *
 * Revision 1.2  1999/06/17 05:39:45  thodes
 *   Updated the inital checkin to append the "Log" field and
 * convert CR/LF to CR (for win/unix interop).
 *
 *   The inital checkin lower-cased directrory names, and omitted
 * many dirs/files that will added later, e.g., MoDAL stuff.
 *
 * All of the above will need to be done to all VSS-to-CVS
 * converted sources.  In summary, in moving from VSS to CVS, do this:
 *  - lower-case dir names
 *  - CR/LF --> CR
 *  - append CVS "Log" entties
 *
 * (a script that helps with #2 and #3 is in
 *     tspaces1:~thodes/bin/update-keywords.sh)
 * 
 */